package zhklappoint.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import zhklappoint.annotation.IgnoreAuth;
import zhklappoint.annotation.LoginUser;
import zhklappoint.entity.Activity;
import zhklappoint.entity.Company;
import zhklappoint.entity.UserActivityMid;
import zhklappoint.entity.WXUser;
import zhklappoint.entity.vo.ActivityMidVo;
import zhklappoint.enums.ENUM_ISDELETE;
import zhklappoint.enums.ENUM_SUCESS;
import zhklappoint.service.InsertIntoActivityInfoService;
import zhklappoint.service.InsertIntoCompanyInfoService;
import zhklappoint.service.UserActivityMidService;
import zhklappoint.service.WXUserService;
import zhklappoint.util.ResponseBean;
import zhklappoint.util.Tools;

/***
 * 前端接口
 * @author eagle
 *
 */
@Controller
@CrossOrigin
@RequestMapping(value="/uni/api",produces = "text/html;charset=UTF-8")
public class ActivityController {
	
	@Autowired
	private InsertIntoCompanyInfoService ics;
	@Autowired
	private InsertIntoActivityInfoService iai;
	@Autowired
	private WXUserService userService;
	@Autowired
	private UserActivityMidService uams;
	
	
	//获取活动详情
	@RequestMapping(value="/getActivityInfoDetail",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getActivityInfoDetail(String aid,@LoginUser WXUser user) {
    	Activity a = iai.getActivityById(aid);
    	if(ObjectUtils.isEmpty(a)) {
    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "数据错误");
    	}
//    	Company c = new Company();
//    	c.setWxUserId(user.getId());
    	Company c=ics.getCompanyById(a.getComId());
    	Page<Company> pcom = ics.getCompanyList(c, 1, 10);
//    	if(pcom.getTotalElements()!=1) {
//    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "获取失败");
//    	}
//    	c=pcom.getContent().get(0);
    	if(ObjectUtils.isEmpty(c)) {
    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "数据错误");
    	}
    	if(!a.getComId().equals(c.getId())) {
    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "数据错误");
    	}
    	Map<String,Object> maps = new HashMap<String,Object>();
    	maps.put("active", a);
    	maps.put("company", c);
    	maps.put("imgpath", Tools.splitString("backimg","indexpage",0));
    	if(ObjectUtils.isEmpty(a.getImgUrlback())) {
    		maps.put("backImg", "");
    	}else {
    		maps.put("backImg", Tools.splitString(a.getImgUrlback(), "backimg","indexpage",0));
    	}
    	return ResponseBean.of(maps,ENUM_SUCESS.SUCESS.value , "获取成功");
    }
	//获取活动详情
		@RequestMapping(value="/getMyActivityInfoDetail",produces = "text/html;charset=UTF-8")
		@ResponseBody
		public String getMyActivityInfoDetail(String uaid,@LoginUser WXUser user) {
			UserActivityMid uam = uams.getUserActivityMidById(uaid);
	    	if(ObjectUtils.isEmpty(uam)) {
	    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "此预定不存在");
	    	}
	    	Activity a = iai.getActivityById(uam.getActivId());
	    	if(ObjectUtils.isEmpty(a)) {
	    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "数据错误");
	    	}
	    	Company c = ics.getCompanyById(a.getComId());
	    	if(ObjectUtils.isEmpty(c)) {
	    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "数据错误");
	    	}
	    	Map<String,Object> maps = new HashMap<String,Object>();
	    	maps.put("active", a);
	    	maps.put("company", c);
	    	maps.put("imgpath", Tools.splitString("backimg","indexpage",0));
	    	maps.put("uam",uam);
	    	if(ObjectUtils.isEmpty(a.getImgUrlback())) {
	    		maps.put("backImg", "");
	    	}else {
	    		maps.put("backImg", Tools.splitString(a.getImgUrlback(), "backimg","indexpage",0));
	    	}
	    	return ResponseBean.of(maps,ENUM_SUCESS.SUCESS.value , "获取成功");
	    }

		
		//取消预约项目
		@RequestMapping(value="/deleteAppointActive",produces = "text/html;charset=UTF-8")
		@ResponseBody
		public String deleteAppointActive(String uaId,@LoginUser WXUser user) {
			UserActivityMid uam = uams.getUserActivityMidById(uaId);
			if(ObjectUtils.isEmpty(uam)) {
	    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "未找到此预约");
	    	} 
			if(!uam.getWxuserId().equals(user.getId())) {
				return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "数据有误");
			}
			uam.setIsdelete(ENUM_ISDELETE.DELETED.value);
			uams.saveUserActivityMid(uam);
			return ResponseBean.of(null,ENUM_SUCESS.SUCESS.value , "取消成功");
		}
	//预定项目
	@RequestMapping(value="/submitAppointActive",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String submitAppointActive(String aid,Long begTime,Long endTime,String choseObj,@LoginUser WXUser user) {
		UserActivityMid uam = new UserActivityMid();
		uam.setWxuserId(user.getId());
		Activity a = iai.getActivityById(aid);
    	if(ObjectUtils.isEmpty(a)) {
    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "未找到活动");
    	} 
    	uam.setActivId(a.getId());
    	uam.setComId(a.getComId());
    	
    	if(!ObjectUtils.isEmpty(a.getStatus())&&a.getStatus()==1) {//预约中有时间约束
    		if(ObjectUtils.isEmpty(begTime)||ObjectUtils.isEmpty(endTime)||begTime==0l||endTime==0l) {
    			return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "当前活动的预约时间段有误");
    		}
    		uam.setBegTime(begTime);
    		uam.setEndTime(endTime);
    	}
    	if(a.getIsRepeat()==1) {//有预约重复限制   如果频率内返回不能预约
    		if(ObjectUtils.isEmpty(a.getTimesRate())||a.getTimesRate()<=0) {
    			return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "请设置重复频率");
    		}
    		Page<UserActivityMid> puams = Page.empty();
        	try {
        		puams=uams.getUserTodayActtiList(uam, a.getIsRepeat(), a.getTimesRate(), 1, 10);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
        	if(puams.getTotalElements()>0) {
        		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "您已预约此项目");
        	}
        	if(!ObjectUtils.isEmpty(a.getIsChose())&&a.getIsChose()==1&&!ObjectUtils.isEmpty(a.getStatus())&&a.getStatus()==1) {
        		if(ObjectUtils.isEmpty(begTime)||ObjectUtils.isEmpty(endTime)||begTime==0l||endTime==0l) {
        			return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "当前活动的预约时间段有误");
        		}
        		if(ObjectUtils.isEmpty(choseObj)) {
        			return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "请选择服务对象");
        		}
        		UserActivityMid uam1 = new UserActivityMid();
        		uam1.setActivId(a.getId());
        		uam1.setComId(a.getComId());
            	uam1.setBegTime(begTime);
            	uam1.setEndTime(endTime);
        		uam1.setChoseObj(choseObj);
        		Page<UserActivityMid> puams1 = Page.empty();
        		puams1=uams.getUserTodayActtiList(uam1, 2, a.getTimesRate(), 1, 10);
        		if(puams1.getTotalElements()>0) {
        			String timeStr="";
        			for(int i=0;i<puams1.getTotalElements();i++) {
        				if(i==puams1.getTotalElements()-1) {
        					timeStr+=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(puams1.getContent().get(i).getBegTime())+"~"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(puams1.getContent().get(i).getEndTime());
        				}else {
        					timeStr+=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(puams1.getContent().get(i).getBegTime())+"~"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(puams1.getContent().get(i).getEndTime())+";;;\r\n";
        				}
        			}
        			return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "服务对象被占用，当前服务对象，已被预约的时间段，包含："+timeStr);
        		}
        		uam.setChoseObj(choseObj);//需要验证当前时间段是否暂用了服务对象
        	}else if(!ObjectUtils.isEmpty(a.getIsChose())&&a.getIsChose()==1&&a.getStatus()!=1){
        		uam.setChoseObj(choseObj);//无要求，可以无视条件的选择服务对象
        	}
    	}
    	if(a.getIsPay()==1) {
    		uam.setStatus(1);
    	}else {
    		uam.setStatus(0);
    	}
    	UserActivityMid newuam = uams.saveUserActivityMid(uam);
    	return ResponseBean.of(newuam,ENUM_SUCESS.SUCESS.value , "预约成功");
	}
	//获取我预约过得活动
	@RequestMapping(value="/getMyActivityList",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getMyActivityList(Integer page,Integer size,String comId,@LoginUser WXUser user) {
    	if(ObjectUtils.isEmpty(page)) {
    		page=1;
    	}
    	if(ObjectUtils.isEmpty(size)) {
    		size=100;
    	}
    	UserActivityMid userActivityMid=new UserActivityMid();
    	userActivityMid.setComId(comId);
    	userActivityMid.setWxuserId(user.getId());
    	Page<UserActivityMid> uamList = uams.getUserActtiList(userActivityMid, page, size);
    	List<ActivityMidVo> lamvs = new ArrayList<ActivityMidVo>();
    	for(UserActivityMid uam : uamList) {
    		List<String> activeTopickList=new ArrayList<String>();//把当前预约过的用户头像加入到项目中
    		UserActivityMid uam1=new UserActivityMid();
    		uam1.setComId(comId);
    		uam1.setActivId(uam.getActivId());
        	Page<UserActivityMid> uam1List = uams.getUserActtiList(uam1, 1, 100);
    		for(UserActivityMid um1:uam1List) {
    			WXUser usr = userService.findById(um1.getWxuserId());
    			activeTopickList.add(usr.getAvatar());
    		}
    		Activity a= iai.getActivityById(uam.getActivId());
    		ActivityMidVo avo = a.cloneToActivityVo(a);
//    		System.out.println("activeID:"+avo.getId());
//    		System.out.println("uamID:"+uam.getActivId());
    		avo.setBegTime(uam.getBegTime());
    		avo.setEndTime(uam.getEndTime());
    		avo.setUaId(uam.getId());
    		avo.setActiveId(avo.getId());
    		avo.setId(uam.getId());//由于前段遍历中需要有唯一标识 于是把当前返回活动的vo对象id赋值为中间表的id
    		avo.setActiveTopickList(activeTopickList);
    		lamvs.add(avo);
    	}
    	Map<String,Object> mss = new HashMap<String,Object>();
    	mss.put("baseUrl", Tools.splitString("backimg","indexpage",0));
    	mss.put("activList", lamvs);
    	return ResponseBean.of(mss,ENUM_SUCESS.SUCESS.value , "获取成功");
    }
	
	//获取可预约活动
	@IgnoreAuth
    @RequestMapping(value="/getActivityList",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getActivityList(Integer page,Integer size,String comId) {
    	if(ObjectUtils.isEmpty(page)) {
    		page=1;
    	}
    	if(ObjectUtils.isEmpty(size)) {
    		size=100;
    	}
    	Map<String,Object> mss = new HashMap<String,Object>();
    	mss.put("baseUrl", Tools.splitString("backimg","indexpage",0));
    	Activity a = new Activity();
    	a.setComId(comId);
    	Page<Activity> pas = iai.getActivityList(a, page, size);
    	for(Activity avo:pas) {//把当前预约过的用户头像加入到项目中
    		List<String> activeTopickList=new ArrayList<String>();
    		UserActivityMid uam1=new UserActivityMid();
    		uam1.setComId(comId);
    		uam1.setActivId(avo.getId());
        	Page<UserActivityMid> uam1List = uams.getUserActtiList(uam1, 1, 100);
    		for(UserActivityMid um1:uam1List) {
    			WXUser usr = userService.findById(um1.getWxuserId());
    			activeTopickList.add(usr.getAvatar());
    		}
    		avo.setActiveTopickList(activeTopickList);
    	}
    	mss.put("activList", pas.getContent());
    	return ResponseBean.of(mss,ENUM_SUCESS.SUCESS.value , "获取成功");
    }
	
	//获取活动列表
    @RequestMapping(value="/getAdminActivity",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getAdminActivity(Integer page,Integer size,@LoginUser WXUser user) {
    	if(ObjectUtils.isEmpty(page)) {
    		page=1;
    	}
    	if(ObjectUtils.isEmpty(size)) {
    		size=100;
    	}
    	Company c = new Company();
    	c.setWxUserId(user.getId());
    	Page<Company> pcom = ics.getCompanyList(c, 1, 10);
    	if(pcom.getTotalElements()!=1) {
    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "获取失败");
    	}
    	c=pcom.getContent().get(0);
    	Activity a = new Activity();
    	a.setComId(c.getId());
    	Page<Activity> pas = iai.getActivityList(a, page, size);
    	return ResponseBean.of(pas.getContent(),ENUM_SUCESS.SUCESS.value , "获取成功");
    }
    
    //新增活动的方法
    @RequestMapping(value="/saveActivity",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String saveActivity(Activity activity,@LoginUser WXUser user) {
    	if(activity.getIsRepeat()==1) {
    		if(ObjectUtils.isEmpty(activity.getStatus())||activity.getStatus()==0) {
    			return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "开启时间按钮才能设置重复频率");
    		}
    		if(ObjectUtils.isEmpty(activity.getTimesRate())||activity.getTimesRate()<=0) {
    			return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "你选择了重复频率却没有设置频率");
    		}
    	}else {
    		activity.setTimesRate(0);
    	}
    	Company c = new Company();
    	c.setWxUserId(user.getId());
    	Page<Company> pcom = ics.getCompanyList(c, 1, 10);
    	if(pcom.getTotalElements()!=1) {
    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "数据错误");
    	}
    	Boolean b= false;
    	for(Company cm:pcom.getContent()) {
    		if(cm.getId().equals(activity.getComId())) {
    			b=true;
    			break;
    		}
    	}
    	if(!b) {
    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "数据错误");
    	}
    	iai.saveActivity(activity);
    	return ResponseBean.of(ENUM_SUCESS.SUCESS.value , "成功发布活动");
    }
    
	//获取活动详情
	@RequestMapping(value="/deleteActivityData",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String deleteActivityData(String aid,@LoginUser WXUser user) {
    	Company c = new Company();
    	c.setWxUserId(user.getId());
    	Page<Company> pcom = ics.getCompanyList(c, 1, 10);
    	if(pcom.getTotalElements()!=1) {
    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "获取失败");
    	}
    	c=pcom.getContent().get(0);
    	Activity a = iai.getActivityById(aid);
    	if(!ObjectUtils.isEmpty(a)&&!a.getComId().equals(c.getId())) {
    		return ResponseBean.of(null,ENUM_SUCESS.FAILED.value , "数据错误");
    	}
    	iai.deleteActivity(a);
    	return ResponseBean.of(null,ENUM_SUCESS.SUCESS.value , "删除成功");
    }


}